<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表格操作</title>
    <style>
        a{
            text-decoration: none;
        }

        table{
            background: #e4b9c0;
            color: #2aabd2;
        }
    </style>
</head>
<body>

<table border="1" style="border-collapse: collapse;text-align: center" id="tab"  cellpadding="10" width="400px" height="20px" >
    <tr>
        <th>编号</th>
        <th>名称</th>
        <th>价格</th>
        <th>操作</th>
    </tr>
    <tr id="id1">
        <td>1</td>
        <td>水</td>
        <td>20</td>
        <td><a href='javascript:(0)' onclick="deleteProduct(1)">删除</a></td>
    </tr>
</table>

编号：<input id="code" type="text"><br>
名称：<input id="name" type="text"><br>
价格：<input id="price" type="number"><br>
<button onclick="addProduct()">添加</button>

</body>
<script>


    function addProduct() {
        //获取输入框中的值
        let code = document.getElementById("code").value.trim();
        let name = document.getElementById("name").value.trim();
        let price = document.getElementById("price").value.trim();
        //获取表格对象
        let tab = document.getElementById("tab");
        //获取表格对象行数数组,再拿到行数值
        let length = tab.rows.length;
        //给表格中插入新的行
        let row = tab.insertRow(length);
        //给插入的行设置id
        row.id="id"+length;
        //插入单元格并赋值
        row.insertCell(0).innerHTML=code;
        row.insertCell(1).innerHTML=name;
        row.insertCell(2).innerHTML=price;
        row.insertCell(3).innerHTML="<a href='javascript:(0)' onclick=deleteProduct("+length+")>删除</a>";
    }


    function deleteProduct(pid) {
        //获取删除行
        let row = document.getElementById("id"+pid);
        //获取删除行的索引
        let count = row.rowIndex;
        //获取表格对象
        let tab = document.getElementById("tab");
        //删除
        tab.deleteRow(count);
    }
</script>
</html>